<template>
  <div class="main">
    <div class="basic-box button-bar" >
<!--      <el-input v-model="searchValue" class="searchInput" placeholder="请输入内容" />-->
      <el-button class="button" type="primary" icon="el-icon-plus" @click="toAdd">添加管理员</el-button>
    </div>
    <div class="basic-box" style="width: 100%">
      <el-table ref="table" :data="tableData">
        <el-table-column prop="id" label="id" min-width="150" align="center" />
        <el-table-column prop="userName" label="管理员用户名" min-width="150" align="center" />
        <el-table-column prop="phone" label="手机号码" min-width="150" align="center" />
        <el-table-column prop="role" label="管理员角色" min-width="150" align="center" />
        <el-table-column prop="enabled" label="启用状态" min-width="150" align="center" />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button class="action-button" type="primary" size="small" @click="toDetail(scope.row)">查看</el-button>
            <el-button class="action-button" type="success" size="small" @click="toEdit(scope.$index)">编辑</el-button>
            <el-button class="action-button" type="danger" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination">
      <span class="demonstration">直接前往</span>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="400">
      </el-pagination>
    </div>

    <!--    弹窗类组件-->
    <el-dialog title="修改管理员的状态" :visible.sync="isEditMode" width="20%" center>
      <div>
        <div class="cell">
          <div class="cell-title-edit">启用状态：</div>
          <div class="cell-content">
            <el-select v-model="editValue['enabled']" placeholder="请选择启用状态" style="width: 100%">
              <el-option v-for="item in enabled" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </div>
        </div>
        <div class="cell">
          <div class="cell-title-edit">角色类型：</div>
          <div class="cell-content">
            <el-select v-model="editValue['role']" placeholder="请选择角色类型" style="width: 100%">
              <el-option v-for="item in role" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </div>
        </div>
      </div>


      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditMode = false">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog title="添加管理员" :visible.sync="isAddMode" width="20%" center>
      <el-form ref="registerForm" :model="registerForm" :rules="registerRules"  autocomplete="on" label-position="left">
        <el-form-item prop="username"  >
          <div class="form-item">
            <svg-icon class="form-item-icon" icon-class="user" />
            <div class="form-item-title">用户名</div>
            <el-input class="form-item-input" ref="username" v-model="registerForm.username" placeholder="Username" name="username" type="text" tabindex="1" autocomplete="off"/>
          </div>
        </el-form-item>
        <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
          <el-form-item prop="password" >
            <div class="form-item">
              <svg-icon class="form-item-icon" icon-class="password" />
              <div class="form-item-title">初始密码</div>
              <el-input class="form-item-input" :key="passwordType" ref="password" v-model="registerForm.password" :type="passwordType" placeholder="Password" name="password" tabindex="2" autocomplete="on" @keyup.native="checkCapslock" @blur="capsTooltip = false" @keyup.enter.native="handleLogin"/>
              <span class="form-item-icon" @click="showPwd"><svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" /></span>
            </div>
          </el-form-item>
        </el-tooltip>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddMode = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="confirmAdd">添 加</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import { getTotalBookList } from '@/api/book.js'
  import { validUsername } from '@/utils/validate'
  import { getUserList , enableUser} from '@/api/user'
  export default {
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!validUsername(value)) {
          callback(new Error('Please enter the correct user name'))
        } else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('The password can not be less than 6 digits'))
        } else {
          callback()
        }
      }
      return {
        searchValue: '',
        showPassword:false,
        inputType:'text',
        isEditMode: false,
        isAddMode:false,
        editValue: '',
        editIndex: '',
        enabled:[
          { value: '0', label: '禁用' },
          { value: '1', label: '启用' },
        ],
        role:[
          { value: 'ROLE_USER', label: '一般游客' },
          { value: 'ROLE_ADMIN', label: '管理员' },
          { value: 'admin', label: '系统管理员' },
        ],
        tableData: [],
        page: 1,
        size: 7,
        capsTooltip: false,
        registerForm: {
          username: 'user',
          password: '123456'
        },
        registerRules: {
          username: [{ required: true, trigger: 'blur', validator: validateUsername }],
          password: [{ required: true, trigger: 'blur', validator: validatePassword }]
        },
        passwordType: 'password',
      }
    },
    mounted() {
      this.getTableData()
      for (var i = 0; i < this.tableData.length; i++) {
        this.tableData[i]['num'] = Math.round(Math.random() * 10)
      }
    },
    methods: {
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.size = `${val}`
        this.page = 1
        this.getTableData()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.page = `${val}`
        this.getTableData()
      },
      toAdd(){
        this.isAddMode = true
      },
      toDetail(row) {
        this.$router.push({ path: '../userDetail', query: { 'name': this.tableData[row].name }})
      },
      checkCapslock(e) {
        const { key } = e
        this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      toEdit(index) {
        this.editIndex = index
        this.editValue ={ enabled:'', role:'' }
        this.isEditMode = true
      },
      confirmAdd(){
        this.$refs.registerForm.validate(valid => {
          if (valid) {
          //  发送表单
            this.isAddMode=false
          } else {
            console.log('error submit!!')
            return false
          }
        })

      },

      confirmEdit() {
        if(this.editValue.enabled !== ''){
          var old = this.tableData[this.editIndex].enabled === '启用' ? 1 : 0
          console.log(old)
          console.log(this.editValue.enabled)
          if(old !== this.editValue.enabled){
            // console.log(old)
            enableUser({ id:this.tableData[this.editIndex].id}).then(
              window.location.reload()
            )
          }
        }
        this.editValue = ''
        this.editIndex = ''
        this.isEditMode = false
        //    发送表单
      },
      getTableData(){
        getUserList(this.page,this.size).then(
          res =>{
            this.tableData = []
            console.log(res)
            for(var i = 0;i < res.data.table.length;i++){
              if(res.data.table[i].roles[0] !== 'ROLE_USER'){
                var element = res.data.table[i]
                element.roles = element.roles[0]
                element.enabled = element.enabled === 1 ? '启用':'禁止'
                switch (element.roles) {
                  case 'ROLE_ADMIN':{
                    element.role = '管理员'
                    break;
                  }
                  case 'admin':{
                    element.role = '系统管理员'
                    break;
                  }
                }
                this.tableData.push(element)
              }
            }


          }
        )
      }
    }
  }
</script>

<style scoped lang="less">
  .main{
    margin:  40px 40px 0 40px;
    width: 80%;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
  .basic-box{
    padding: 40px;
    margin-bottom: 20px;
    border-radius: 10px;
  }
  .action-button{
    border-radius: 5px;
    padding: 5px 10px;
    /*border: 1px solid #a2a2a2;*/
  }
  .button-bar{
    /*position: absolute;*/
    /*top: 40px;*/
    padding: 10px;
    align-self: flex-end;
    /*width: 30%;*/
    display: flex;
    flex-direction: row;
    .searchInput{
      width: 200px;
    }
    .button{
      /*margin-left: 20px;*/
    }
  }
  .pagination{
    margin: 30px;
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items:center;
    justify-content: center;
  }
  .password{
    width: 100px;
    margin: 0 auto;
    border: #a2a2a2;
    background-color: #b2e8d7;
    border-radius: 10px;
    color: #f0f0f0;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select:none;
  }
  .cell{
    display: flex;
    flex-direction: row;
    align-items: center;
    margin:10px;
    .cell-title-edit{
      /*font-size: 20px;*/
      font-weight:600;
      color: #11A983;
      width: 80px;
    }
    .cell-content{
      /*font-size: 20px;*/
      font-weight: 500;
    }
  }
  .form-item{
    display: flex;
    flex-direction: row;
    align-items: center;
    .form-item-icon{
        /*padding: 20px;*/
      margin:0 10px;
    }
    .form-item-title{
      width: 80px;
      color: #11A983;
      font-weight: 600;
    }
    .form-item-input{
      width: 55%;
    }
  }

</style>
